<template>
  <div class="user">
    <page-search
      :search-config="searchConfig"
      @query-click="handleQueryClick"
      @reset-click="handleResetClick"
    />
    <tabel-context
      :content-config="contextConfig"
      @newClick="handelUser"
      @editClick="handleEditClick"
      ref="contentRef"
    >
      <template #enable="scope">
        <el-button size="small" :type="scope.row.enable ? 'primary' : 'danger'" plain>
          {{ scope.row.enable ? '启用' : '禁用' }}
        </el-button>
      </template>
    </tabel-context>
    <page-modal :modal-config="modalConfigRef" ref="userModal" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

import PageSearch from '@/components/page-search/page-search.vue'
import tabelContext from '@/components/tabel-context/tabel-context.vue'
import pageModal from '@/components/page-modal/page-modal.vue'
import searchConfig from './config/search.config'
import contextConfig from './config/context.config'
import modalConfig from './config/modal.config'
import userMainStore from '@/store/main/main'
import useTabelContext from '@/hooks/useTabelContent'

const modalConfigRef = computed(() => {
  const mainStore = userMainStore()
  const entireRoles = mainStore.entireRoles.map((item) => {
    return { label: item.name, value: item.id }
  })
  const entirDepartment = mainStore.entireDepartments.map((item) => {
    return { label: item.name, value: item.id }
  })
  modalConfig.formItems.forEach((item: any) => {
    if (item.prop === 'roleId') {
      return item.options.push(...entireRoles)
    }
    if (item.prop === 'departmentId') {
      console.log(item, entireRoles)
      return item.options.push(...entirDepartment)
    }
  })

  return modalConfig
})

const userModal = ref<InstanceType<typeof pageModal>>()
function handelUser() {
  console.log(modalConfig.formItems.findIndex((item) => item.prop === 'password'))
  if (modalConfig.formItems.findIndex((item) => item.prop === 'password') === -1) {
    modalConfig.formItems.push({
      type: 'input',
      label: '密码',
      prop: 'password',
      placeholder: '请输入密码'
    })
  }
  userModal.value?.setModalVisible()
}

// 搜索事件
const { contentRef, handleQueryClick, handleResetClick } = useTabelContext()

// 删除和编辑事件
function handleEditClick(itemData: any) {
  if (modalConfig.formItems.findIndex((item) => item.prop === 'password') !== -1) {
    modalConfig.formItems.pop()
  }
  userModal.value?.setModalVisible(false, itemData)
}
</script>

<style lang="less" scoped>
.user {
  border-radius: 8px;
  overflow: hidden;
}
</style>
